package com.sise.cn.api.common.service;

import com.sise.cn.api.common.po.Order;
import com.sise.cn.api.common.po.OrderItem;
import com.sise.cn.api.enumerate.ServerResponseEnum;
import com.sise.cn.api.exception.OrderException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author 龚秀峰
 * @version 1.0
 * @date 2020/6/14 11:34
 * 订单关联性校验处理
 */
@Slf4j
@Component
public class OrderAssociateItemHandler extends BaseOrderHandler {

    @Resource
    private OrderService orderService;
    @Resource
    private OrderItemService orderItemService;

    public OrderAssociateItemHandler() {
        super("订单关联订单项检查处理");
    }

    @Override
    public boolean processOrder(Order order) {
        //订单号是否重复的检查
        final List<Order> orderByOrderCode = orderService.getOrderByOrderCode(order.getOrderCode());
        if (!orderByOrderCode.isEmpty()) {
            throw new OrderException(ServerResponseEnum.ORDER_REPEAT_ERROR);
        }
        //订单项关联检查
        List<Long> orderItemIds = order.getOrderItemIds();
        if (orderItemIds == null || orderItemIds.isEmpty()) {
            throw new OrderException(ServerResponseEnum.ORDER_RELATION_NONE);
        }
        for (Long orderItemId : orderItemIds) {
            final OrderItem orderItem = orderItemService.getOrderItemById(orderItemId);
            if (orderItem == null) {
                log.error("订单号:{}关联的订单项ID:{}不存在！", order.getOrderCode(),orderItemId);
                throw new OrderException(ServerResponseEnum.ORDER_ITEM_SELECT_FAIL);
            }
        }
        return getNextOrderHandler() == null || getNextOrderHandler().processOrder(order);
    }
}
